<template>
  <div>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="账号" prop="username">
        <el-input v-model="ruleForm.username"></el-input>
      </el-form-item>
      <el-form-item label="员工姓名" prop="name">
        <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="ruleForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="ruleForm.sex">
          <el-radio label="1">男</el-radio>
          <el-radio label="2">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="身份证号" prop="idNumber">
        <el-input v-model="ruleForm.idNumber"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >保存</el-button
        >
        <el-button @click="$router.push({ name: 'Employee' })">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  addEmployee,
  getEmployeeById,
  changeEmployeesStatus,
} from "@/api/employee";
export default {
  created() {
    if (this.$route.query.id) {
      getEmployeeById(this.$route.query.id).then((res) => {
        this.ruleForm = res.data;
      });
    }
  },
  data() {
    return {
      ruleForm: {
        username: "",
        name: "",
        phone: "",
        sex: "1",
        idNumber: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入账号", trigger: "change" },
        ],
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.isEdit) {
            await changeEmployeesStatus(this.ruleForm);
            this.$message.success("编辑成功");
          } else {
            await addEmployee(this.ruleForm);
            this.$message.success("添加成功");
          }
          this.$router.push({ name: "Employee" });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
  computed: {
    isEdit() {
      return this.$route.query.isEdit === "1";
    },
  },
};
</script>

<style lang="scss" scoped>
.el-form {
  width: 500px;
  margin-left: 100px;
  margin-top: 88px;
}
</style>
